package com.lintf.distributed.transaction.inventory.config;

import com.lintf.distributed.transaction.inventory.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

import java.util.Collections;

@Slf4j
@Configuration
@RefreshScope
public class RetryConfig {

    @Value("${message.retry.max-attempts:3}")
    private int maxAttempts;

    @Value("${message.retry.initial-interval:5000}")
    private long initialInterval;

    @Value("${message.retry.multiplier:2.0}")
    private double multiplier;

    @Value("${message.retry.max-interval:60000}")
    private long maxInterval;

    @Bean
    public RetryTemplate retryTemplate() {
        // 指数退避策略
        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        backOffPolicy.setInitialInterval(initialInterval);
        backOffPolicy.setMultiplier(multiplier);
        backOffPolicy.setMaxInterval(maxInterval);

        // 重试策略：只重试业务异常
        RetryPolicy retryPolicy = new SimpleRetryPolicy(maxAttempts,
                Collections.singletonMap(BusinessException.class, true),
                false); // 默认重试所有异常（但通过retryPolicy控制）

        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setBackOffPolicy(backOffPolicy);
        retryTemplate.setRetryPolicy(retryPolicy);

        // 添加监听器记录重试日志
        retryTemplate.registerListener(new RetryStatisticsListener());
        return retryTemplate;
    }
}